package com.gaoyang.task;

import com.alibaba.fastjson.JSONObject;
import com.gaoyang.domain.MinshengUser;
import com.gaoyang.util.Base64Img;
import com.gaoyang.util.Chaojiying;
import com.gaoyang.util.DateUtils;
import com.gaoyang.util.HttpUtils4Black;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Component;
import sun.net.www.http.HttpClient;

import java.util.*;
import java.util.concurrent.Future;

@Component
public class MinshengTask {

    private Logger logger = LogManager.getLogger(MinshengTask.class);

    String GAOYANG_CODE = "";
    String ZHIQIANG_CODE = "";
    String JIALI_CODE = "";

    private String timeStart = "";
    private String timeEnd = "";
    private String codeTime = "";
    private String codeTimeStart = "";

    String THURSDAY_GIFT = "G201705057259";
    String FRIDAY_GIFT = "G201705057260";
    String SATURDAY_GIFT = "G201705057261";
    String SUNDAY_GIFT = "G201705057262";
//    String MONDAY_GIFT = "G201702078122";

//    private String USERNAME = "testxy222";
    private String USERNAME = "testxy111";
    private String PASSWORD = "4433221";
    private String SOFTID = "96002";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private void getTimes() {
        GregorianCalendar ca = new GregorianCalendar();
        if (ca.get(GregorianCalendar.AM_PM) == 0) {
            codeTime = DateUtils.getTodayStr() + " 10:00:00:000";
            codeTimeStart = DateUtils.getTodayStr() + " 09:59:10:000";
            timeStart = DateUtils.getTodayStr() + " 09:59:57:650";
            timeEnd = DateUtils.getTodayStr() + " 10:00:00:000";
        } else {
            codeTime = DateUtils.getTodayStr() + " 15:00:00:000";
            codeTimeStart = DateUtils.getTodayStr() + " 14:59:10:000";
            timeStart = DateUtils.getTodayStr() + " 14:59:57:650";
            timeEnd =  DateUtils.getTodayStr() + " 15:00:00:000";
//            codeTimeStart = DateUtils.getTodayStr() + " 16:56:10:750";
//            timeStart = DateUtils.getTodayStr() + " 16:56:57:750";
//            timeEnd =  DateUtils.getTodayStr() + " 16:57:01:750";
        }
    }

    @Async
    public Future<String> doTaskOne(MinshengUser user) throws Exception {
        getTimes();
        if (DateUtils.compare_date(new Date(), codeTimeStart) == 1
                && DateUtils.compare_date(new Date(), timeEnd) == -1) {
            if ((!GAOYANG_CODE.equals("") && (GAOYANG_CODE.length() == 5))) {
//                logger.info("高洋验证码正确");
            } else {
                String pic_str = "";
                long timestamp = DateUtils.getTimeByDate(codeTime);
                String url = "https://prefacty.creditcard.cmbc.com.cn/mmc-main-webapp/jcaptcha.img?userKey=" + user.getUserKey() + "&timestamp=" + timestamp;
                logger.info(user.getUsername() + ":" + url);
                byte[] base64 = Base64Img.GetImageByteFromUrl(url);
                String code = Chaojiying.PostPic(USERNAME, PASSWORD, SOFTID, "1005", "5", base64);
                JSONObject jsonObject = JSONObject.parseObject(code);
                String status = jsonObject.getString("err_str");
                if ("OK".equals(status)){
                    pic_str = jsonObject.getString("pic_str");
                }
                logger.info(user.getUsername() + ":" + pic_str.toUpperCase());
                GAOYANG_CODE = pic_str.toUpperCase();
                stringRedisTemplate.opsForValue().set("GAOYANG_CODE", code.toUpperCase());
            }
        } else {
            GAOYANG_CODE = "";
        }
        return getStringFuture(user, GAOYANG_CODE);
    }

    @Async
    public Future<String> doTaskTwo(MinshengUser user) throws Exception {
        getTimes();
        if (DateUtils.compare_date(new Date(), codeTimeStart) == 1
                && DateUtils.compare_date(new Date(), timeEnd) == -1) {
            if ((!JIALI_CODE.equals("") && (JIALI_CODE.length() == 5))) {
//                logger.info("佳丽验证码正确");
            } else {
                String pic_str = "";
                long timestamp = DateUtils.getTimeByDate(codeTime);
                String url = "https://prefacty.creditcard.cmbc.com.cn/mmc-main-webapp/jcaptcha.img?userKey=" + user.getUserKey() + "&timestamp=" + timestamp;
                logger.info(user.getUsername() + ":" + url);
                byte[] base64 = Base64Img.GetImageByteFromUrl(url);
                String code = Chaojiying.PostPic(USERNAME, PASSWORD, SOFTID, "1005", "5", base64);
                JSONObject jsonObject = JSONObject.parseObject(code);
                String status = jsonObject.getString("err_str");
                if ("OK".equals(status)){
                    pic_str = jsonObject.getString("pic_str");
                }
                logger.info(user.getUsername() + ":" + pic_str.toUpperCase());
                JIALI_CODE = pic_str.toUpperCase();
                stringRedisTemplate.opsForValue().set("JIALI_CODE", code.toUpperCase());
            }
        } else {
            JIALI_CODE = "";
        }
        return getStringFuture(user, JIALI_CODE);
    }
    @Async
    public Future<String> doTaskThree(MinshengUser user) throws Exception {
        getTimes();
        if (DateUtils.compare_date(new Date(), codeTimeStart) == 1
                && DateUtils.compare_date(new Date(), timeEnd) == -1) {
            if ((!ZHIQIANG_CODE.equals("") && (ZHIQIANG_CODE.length() == 5))) {
//                logger.info("志强验证码正确");
            } else {
                String pic_str = "";
                long timestamp = DateUtils.getTimeByDate(codeTime);
                String url = "https://prefacty.creditcard.cmbc.com.cn/mmc-main-webapp/jcaptcha.img?userKey=" + user.getUserKey() + "&timestamp=" + timestamp;
                logger.info(user.getUsername() + ":" + url);
                byte[] base64 = Base64Img.GetImageByteFromUrl(url);
                String code = Chaojiying.PostPic(USERNAME, PASSWORD, SOFTID, "1005", "5", base64);
                JSONObject jsonObject = JSONObject.parseObject(code);
                String status = jsonObject.getString("err_str");
                if ("OK".equals(status)){
                    pic_str = jsonObject.getString("pic_str");
                }
                logger.info(user.getUsername() + ":" + pic_str.toUpperCase());
                ZHIQIANG_CODE = pic_str.toUpperCase();
                stringRedisTemplate.opsForValue().set("ZHIQIANG_CODE", code.toUpperCase());
            }
        } else {
            ZHIQIANG_CODE = "";
        }
        return getStringFuture(user, ZHIQIANG_CODE);
    }

    private Future<String> getStringFuture(MinshengUser user, String code)  throws Exception {
        String returnStr = "";
        if (DateUtils.compare_date(new Date(), timeStart) == 1
                && DateUtils.compare_date(new Date(), timeEnd) == -1) {
            Map<String, String> paramMap = new HashMap();
            String channelType = "activityday";
            String actyId = "A20170505897";
            String giftId = SUNDAY_GIFT;
            if (DateUtils.getWeekOfDate().equals("星期五")) {
                giftId = FRIDAY_GIFT;
            } else if (DateUtils.getWeekOfDate().equals("星期四")) {
                giftId = THURSDAY_GIFT;
            } else if (DateUtils.getWeekOfDate().equals("星期六")) {
                giftId = SATURDAY_GIFT;
            } else if (DateUtils.getWeekOfDate().equals("星期日")){
                giftId = SUNDAY_GIFT;
            } else {
//                channelType = "";
//                actyId = "A20170206786";
//                giftId = MONDAY_GIFT;
            }
            paramMap.put("channelType", channelType);
            paramMap.put("actyId", actyId);
            paramMap.put("giftId", giftId);
            paramMap.put("giftNum", "1");
            paramMap.put("groupId", "");
            paramMap.put("isCaptcha", "true");
            paramMap.put("jcaptchaText", code);
//        logger.info(paramMap.get("jcaptchaText"));
            paramMap.put("merchantId", "0007135");
            paramMap.put("timp", "405b150a38f44f4ef489b44c4987927f");
            paramMap.put("userKey", user.getUserKey());
            returnStr += HttpUtils4Black.sendMinshengGet("https://prefacty.creditcard.cmbc.com.cn/mmc-main-webapp/main/Order.json?", paramMap, user.getCmbc_uuid());
            returnStr += " " + new Date() + " " + user.getUsername() + "完成";
//            System.out.println(returnStr);
        }
        else {
//            returnStr = user.getUsername() + " 民生" + "时间还不到";
        }
        return new AsyncResult<String>(returnStr);
    }


}